package com.cxf.windex.biz;

import com.cxf.windex.base.biz.BaseBiz;
import com.cxf.windex.base.constant.UserConstant;
import com.cxf.windex.base.util.IdUtil;
import com.cxf.windex.entity.Activity;
import com.cxf.windex.enums.ActivityEnum;
import com.cxf.windex.mapper.ActivityMapper;
import com.github.pagehelper.PageHelper;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @program: business_needs
 * @description:
 * @author: chenxf
 * @create: 2018-10-29 09:54
 **/
@Service
public class ActivityBiz extends BaseBiz<ActivityMapper,Activity> {

  /**
   * 活动列表
   *
   * @param limit 数量
   * @param offset 页码
   * @param orderStr  排序(升序或者降序)
   * @param range 适用范围
   * @param name  活动名称
   * @param type  操作
   * @return
   */
  public List<Activity> list(int limit, int offset,  String orderStr,String name,String range,String type) {
    Example example = new Example(Activity.class);
    Example.Criteria criteria = example.createCriteria();
    if(StringUtils.isNotBlank(name)){
      criteria.andLike("name", "%"+ name+"%" );
    }
    if(StringUtils.isNotBlank(type)){
      criteria.andEqualTo("type", type);
    }
    criteria.andEqualTo("ranges", range);
    example.setOrderByClause("status desc,crt_time " + orderStr);
    PageHelper.startPage(offset, limit);
    return selectByExample(example);
  }

  /**
   * 根据 操作、金额 时间，查询符合条件的活动
   * @param activityEnum 操作
   * @param money 金钱
   * @param range 适用范围
   * @return 享受奖励
   */
  public Activity queryActivity(String range,ActivityEnum activityEnum,BigDecimal money) {
    Example example = new Example(Activity.class);
   example.createCriteria()
        .andEqualTo("type",  activityEnum.getKey() )
       .andEqualTo("ranges",range)
       .andLessThanOrEqualTo("money",money)
        .andEqualTo("status", 1)
        .andLessThan("bTime",new Date())
        .andGreaterThan("eTime", new Date());
    example.setOrderByClause("("+money+"-money)  asc " );
    List<Activity> items=selectByExample(example);
    if(items.size()>0){
       return  items.get(0);
    }
    return null;
  }
  /**
   * 保存活动
   * @param entity
   */
  public void save(Activity entity){
    if(entity.getId()==null|| StringUtils.isBlank(entity.getId())){
      entity.setId(UserConstant.ACTIVITY_ID_PREX+new IdUtil(5,1).nextId());
      insertSelective(entity);
    }else{
      updateSelectiveById(entity);
    }
  }
}
